module.exports = app => {
  const express = require('express')
  const router = express.Router({
    mergeParams: true
  })

  const resourceMiddleware = require('../../middleWare/resource')
  const authMiddleware = require('../../middleWare/auth')
  const throwError = require('../../middleWare/throwErr')

  // router.get("*", function (req, res, next) {
  //   console.log(req.params);
  //   console.log(req.query);
  //   console.log(req.body);
  //   next()
  // })
  // function getAuth(req,res,next){
  // }

  /**post方法路由 */
  router.post('/', async (req, res) => {
    const model = await req.Model.create(req.body)
    // resful风格返回码 201 CREATED - [POST/PUT/PATCH]：用户新建或修改数据成功。
    res.status(201).send(model)
  })

  /**get方法 */
  router.get('/', async (req, res) => {
    let queryOptions = {}
    if (req.Model.modelName === 'Category') {
      queryOptions.populate = 'parent'
    }
    const items = await req.Model.find().setOptions(queryOptions)
    // const count = items.length
    // console.log(count)
    res.send({
      items
    })
  })

  /**get/:id 获取编辑数据 */
  router.get('/:id', async (req, res) => {
    const items = await req.Model.findById(req.params.id)
    res.send(items)
  })

  /**put/:id 保存编辑数据 */
  router.put('/:id', async (req, res) => {
    // console.log('req.params =>', req.params)
    // console.log('req.body =>',req.body)
    const items = await req.Model.findByIdAndUpdate(req.params.id, req.body)
    res.status(201).send(items)
  })

  /**delete 删除数据 */
  router.delete('/:id', async (req, res) => {
    await req.Model.findByIdAndDelete(req.params.id, req.body)
    res.send({
      success: true
    })
  })

  app.use('/admin/api/rest/:resource', authMiddleware(), throwError(), resourceMiddleware(), router)
}